
//
//  GetLinesManager.m
//  GetNumberOfLines
//
//  Created by New on 16/5/30.
//  Copyright © 2016年 New. All rights reserved.
//

#import "GetLinesManager.h"

@implementation GetLinesManager

+ (NSInteger)findNumberOfLinesForString:(NSString *)string size:(CGSize)size font:(UIFont *)font
{
    NSTextStorage *storage = [[NSTextStorage alloc] initWithString:string attributes:@{NSFontAttributeName:font}];
    NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:size];
    textContainer.lineBreakMode = NSLineBreakByTruncatingTail;
    textContainer.maximumNumberOfLines = 0;
    textContainer.lineFragmentPadding = 0;
    
    NSLayoutManager *manager = [[NSLayoutManager alloc] init];
    manager.textStorage = storage;
    [manager addTextContainer:textContainer];
    
    NSInteger numberOfLines = 0;
    NSInteger index = 0;
    NSRange range = NSMakeRange(0, 0);
    
    for (; index < manager.numberOfGlyphs; numberOfLines++) {
        [manager lineFragmentRectForGlyphAtIndex:index effectiveRange:&range];
        index = NSMaxRange(range);
    }
    
    return numberOfLines;
}

@end
